package com.daidai

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.PopupWindow
import com.daidai.tools.G
import java.lang.Exception

fun interface IBack{
    fun onBack()
}
abstract class BasePopWindow{
    private val contextView:View
    var innerWindow:InnerWindow

    constructor(ctx:Context){
        contextView = LayoutInflater.from(ctx).inflate(layoutResId(),null,false)
        val dm = ctx.resources.displayMetrics
        innerWindow = InnerWindow(contextView,dm.widthPixels,dm.heightPixels,true)
        innerWindow.isOutsideTouchable = true
        innerWindow.isTouchable = true
        initView(contextView)
    }

    abstract fun initView(view:View)
    abstract fun layoutResId() : Int

    inner class InnerWindow(contentView:View,width:Int,height:Int,focus:Boolean): PopupWindow(
            contentView,width,height,focus
    ) {

        var backCallback:IBack? = null

        override fun dismiss() {
            val stackTrace = Exception().stackTrace
            G.elog("============================ Begin:")
            stackTrace.forEach {
                G.elog("element:$it")
            }
            G.elog("=========================== End!")
            if(stackTrace.size >= 2 &&
                    "dispatchKeyEvent" == stackTrace[1].methodName){
                // 按了返回键盘
                if(backCallback != null){
                    backCallback?.onBack()
                }else{
                    dismiss2()
                }
            }else{
                dismiss2()
            }
        }

        private fun dismiss2(){
            super.dismiss()
        }
    }
}